package routing;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.junit.Test;
import util.ConnUtil;

/**
 * 可以指定不同的RoutingKey，让交换机根据RoutingKey的不用，将消息路由到不同的队列中。
 * @author TZL
 * @date 2020/8/14
 */
public class Publisher {
    public static final String EXCHANGE_NAME = "routing";
    public static final String INFO_XX_QUEUE = "info-xx";
    public static final String ERROR_DEBUG_XX_QUEUE = "error-debug-xx";

    @Test
    public void publish() throws Exception {
        //1. Conn
        Connection conn = ConnUtil.getConn();
        //2. Channel
        Channel channel = conn.createChannel();


        //3.1 创建Exchange
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT,true,false,null);
        //3.2 创建Queue1
        channel.queueDeclare(INFO_XX_QUEUE,true,false,false,null);
        //3.3 创建Queue2
        channel.queueDeclare(ERROR_DEBUG_XX_QUEUE,true,false,false,null);
        //3.4 queue1绑定到exchange
        channel.queueBind(INFO_XX_QUEUE,EXCHANGE_NAME,"INFO");
        channel.queueBind(INFO_XX_QUEUE,EXCHANGE_NAME,"XX");
        //3.5 queue2绑定到exchange
        channel.queueBind(ERROR_DEBUG_XX_QUEUE,EXCHANGE_NAME,"ERROR");
        channel.queueBind(ERROR_DEBUG_XX_QUEUE,EXCHANGE_NAME,"DEBUG");
        channel.queueBind(ERROR_DEBUG_XX_QUEUE,EXCHANGE_NAME,"XX");

        //4. 发送消息到exchange,指定routingKey
        String xxMsg = "Routing的XX消息!!";
        channel.basicPublish(EXCHANGE_NAME,"XX",null,xxMsg.getBytes());

        String infoMsg = "Routing的INFO消息!!";
        channel.basicPublish(EXCHANGE_NAME,"INFO",null,infoMsg.getBytes());

        String errorMsg = "Routing的ERROR消息!!";
        channel.basicPublish(EXCHANGE_NAME,"ERROR",null,errorMsg.getBytes());

        //5. close
        channel.close();
        conn.close();
    }

}
